import pygame
import sys
import g
from character import Ken
import net
from util import *
from gameobject import objects
import content
from game import Game
import time

class ServerGame(Game):
	def __init__(self, name, zoom = 1):
		Game.__init__(self, zoom)
		self.playersAllReady = False
		self.serverName = name
		self.lastNotify = 0

	def createObject(self, name, owner, *args):
		ctor = objects[name]
		image = content.images["gameobjects"][name + ".png"]
		obj = ctor(image, owner, *args)
		self.objs.append(obj)
		self.netServer.sendCreateObject(name, owner, args)

	def killObject(self, obj):
		self.objsDel.append(obj)

	def initialize(self):
		self.netServer = net.Server(self.serverName)

	def preGameRun(self):
		while not self.playersAllReady:
			self.netServer.update(self)
			t = time.time()
			if t - self.lastNotify > 15:
				self.netServer.notifyServerList()
				self.lastNotify = t
			for evt in pygame.event.get():
				if evt.type == pygame.QUIT:
					sys.exit()


		self.netServer.spawn()

		self.objs.extend(self.chars)

	def netUpdate(self):
		self.netServer.update(self)

		if self.frameNum % 4 == 0:
			self.netServer.sendCharState()
		if self.frameNum % 300 == 0:
			self.netServer.updateLatency()

	def showDebugText(self, text, x, y):
		Game.showDebugText(self, text, x, y)
		self.netServer.sendDebugText(text, x, y)

name = "test"
if(len(sys.argv) > 1):
	name = sys.argv[1]
gGame = ServerGame(name)
g.gGame = gGame
content.loadContent()
gGame.initialize()
gGame.run()
